<template>
  <div class="homePage">
    <div class="homeHeader">
      <div>
        <img :src="icon.mapMarker" alt="">
        <van-dropdown-menu active-color="#000000">
          <van-dropdown-item
            @change="handleChangeCity"
            v-model="currentCity"
            :options="cityOption"
          />
        </van-dropdown-menu>
      </div>
      <van-search
        class="searchBar"
        v-model="searchTxt"
        @search="onSearch"
        shape="round"
        background="#ffc600"
        placeholder="搜索一切你想搜索的内容"
      />
    </div>
    <div class="searchContent container">
      <template v-if="tabName === 'food'">
        <div class="scroll-container">
          <ul class="goodsFilter">
            <li
              :class="{active: activeLevel === item.id}"
              @click="handleSelectRestaurantCategory(item)"
              v-for="item in goodsFilterList"
              :key="item.id">
              <img v-if="item.picFile.url" :src="item.picFile.url" alt="">
              <span>{{ item.name }}</span>
            </li>
          </ul>
        </div>
      </template>
      <van-pull-refresh
        loading-text="刷新中"
        success-text="刷新成功"
        v-model="refreshing"
        @refresh="onRefresh">
        <template v-if="merchantList.length">
          <van-list
            :loading="loading"
            :finished="finished"
            finished-text="我是有底线的"
            @load="onLoad"
            :immediate-check="false"
          >
            <MerchantCard
              class="merchantItem"
              v-for="item in merchantList"
              :merchantData="item"
              :key="item.id"
            />
          </van-list>
        </template>
        <van-empty v-else description="暂无数据" />
      </van-pull-refresh>
      <van-back-top  target=".container"/>
    </div>
    <van-tabbar
      class="tabbarNav"
      v-model="tabName"
      @change="onChangeTab"
      active-color="#000000"
      inactive-color="#575958"
      :placeholder="true">
      <van-tabbar-item name="food">
        <span>美食</span>
        <template #icon="props">
          <img class="tabbarIcon" :src="props.active ? icon.foodActive : icon.food" />
        </template>
      </van-tabbar-item>
      <van-tabbar-item name="business">
        <span>商铺</span>
        <template #icon="props">
          <img class="tabbarIcon" :src="props.active ? icon.shopActive : icon.shop" />
        </template>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>
<script setup>
import { categoryListMethod, merchantListMethod } from "@/api/homePage.js";
import MerchantCard from './merchantCard.vue'
import cityCoordinates from '@/utils/cityCoordinates'
import foodActive from '@/assets/image/icon-food-active.png';
import food from '@/assets/image/icon-food.png';
import shopActive from '@/assets/image/icon-shop-active.png';
import shop from '@/assets/image/icon-shop.png';
import mapMarker from '@/assets/image/map_marker.png';
const icon = reactive({ foodActive, food, shopActive, shop, mapMarker })

//城市选择下拉控件
const currentCity = ref(cityCoordinates[0].cityName);
const cityOption = cityCoordinates.map(item => {
  const { cityName, lon, lat } = item;
  return { text: cityName, value: cityName, lon, lat }
});
const handleChangeCity = () => {
  refreshing.value = true;
  onRefresh();
}

//商品检索
import { useRouter } from 'vue-router'
const router = useRouter()
const searchTxt = ref("");
const onSearch = () => {
  router.push({
    name: 'searchPage',
    query: {
      searchContent: searchTxt.value
    }
  });
}

//分类列表
onMounted(() => { getCategoryList() });
const goodsFilterList = ref([]);
const getCategoryList = async () => {
  categoryListMethod().then((res) => {
    const { data } = res;
    const restaurantCategory = data.find(item => item.name === "餐饮_Restoran");
    const { children } = restaurantCategory;
    goodsFilterList.value = [
      { id: undefined, parentId: restaurantCategory.id, name: "全部", picFile: { url: undefined } },
      ...children
    ];
    //默认检索餐饮
    handleSelectRestaurantCategory(goodsFilterList.value[0])
  })
}

//选中分类
const activeLevel = ref(undefined);
const handleSelectRestaurantCategory = (item) => {
  const { id, parentId } = item;
  if(activeLevel.value === id) {
    //激活全部按钮
    activeLevel.value = undefined;
    searchParams.firstLevel = parentId;
    searchParams.secondLevel = undefined;
  }else {
    activeLevel.value = id;
    searchParams.firstLevel = parentId;
    searchParams.secondLevel = id;
  }
  refreshing.value = true;
  onRefresh();
}

//商家列表参数
const searchParams = reactive({
  name: '',
  firstLevel: '',
  secondLevel: '',
  lon: '',
  lat: '',
  pageNum: 1,
  pageSize: 10,
});

//下拉刷新
const refreshing = ref(false);  //是否处于下拉刷新中
const onRefresh = () => {
  finished.value = false;
  onLoad();
};

//商家列表
const merchantList = ref([]);
const loading = ref(false);  //是否列表加载中
const finished = ref(false); //是否列表全部加载完成
const onLoad = async () => {
  loading.value = true;
  if (refreshing.value) {
    searchParams.pageNum = 1;
  }
  //参数组合
  const cityData = cityOption.find(item => item.value === currentCity.value);
  const { lon, lat } = cityData;
  const params = { ...searchParams, lon, lat };
  //数据请求开始
  const res = await merchantListMethod(params);
  const { rows, total, code } = res;
  //刷新后的数据处理
  if (refreshing.value) {
    merchantList.value = rows;
  }else {
    merchantList.value.push(...rows);
  }
  refreshing.value = false;
  //数据请求结束
  loading.value = false;
  searchParams.pageNum++;
  if(merchantList.value.length >= total) {
    finished.value = true;
  }
}

//底部tab切换
const tabName = ref('food');
const onChangeTab = (value) => {
  if(value === 'food') {
    handleSelectRestaurantCategory(goodsFilterList.value[0])
  }else if(value === 'business') {
    handleSelectRestaurantCategory({ id: undefined, parentId: undefined })
  }
}

</script>
<style lang="less" scoped>
div.homePage {
  width: 100%;
  height: 100%;
  position: relative;
  >.homeHeader {
    height: 120px;
    background: #ffc600;
    padding: 12px;
    box-sizing: border-box;
    >div:first-child {
      display: flex;
      align-items: center;
      justify-content: start;
      margin-bottom: 4px;
      img {
        width: 18px;
        height: 18px;
      }
      ::v-deep .van-dropdown-menu__bar {
        height: 25px;
        background: #ffc600 !important;
        box-shadow: unset !important;
        .van-dropdown-menu__title {
          padding-left: 4px;
          .van-ellipsis {
            font-size: 16px;
            font-weight: bold;
          }
          &::after {
            border-color: transparent transparent #000000 #000000;
          }
        }
      }
    }
    >.searchBar {
      --van-search-padding: 0;
      --van-search-input-height: 48px;
      ::v-deep .van-icon {
        font-size: 18px;
      }
      ::v-deep .van-field__control {
        font-size: 16px;
      }
    }
  }
  >.searchContent {
    overflow: auto;
    height: calc(100% - 120px - 60px + 18px);
    margin-top: -18px;
    border-radius: 24px 24px 0 0;
    background: #f5f5f5;
    padding: 12px;
    .merchantItem:not(:last-child) {
      margin-bottom: 12px;
    }
  }
  >.tabbarNav {
    --van-tabbar-height: 60px;
    .tabbarIcon {
      width: 26px;
      height: 26px;
      margin-bottom: 2px;
    }
  }
}
</style>
<style lang="less" scoped>
.scroll-container {
  overflow-x: auto; /* 允许水平滚动 */
  white-space: nowrap; /* 防止换行 */
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
  ul.goodsFilter {
    height: 48px;
    margin-bottom: 12px;
    display: inline-flex; /* 让 ul 内部元素水平排列 */
    align-items: center;
    justify-content: start;
    li {
      min-width: 72px;
      height: 48px;
      padding: 0 10px;
      box-sizing: border-box;
      border-radius: 29px;
      background: #ffffff;
      display: flex;
      align-items: center;
      justify-content: center;
      &.active {
        background: #ffc600;
      }
      &:not(:last-child) {
        margin-right: 12px;
      }
      img {
        width: 40px;
        height: 40px;
        margin-right: 6px;
        border-radius: 50%;
      }
      span {
        font-size: 16px;
        font-weight: bold;
        white-space: nowrap; /* 确保文本不会被压缩或换行 */
      }
    }
  }
}
</style>
